import  csv
#打开csv文件
# with open('data.csv','r',encoding='utf-8') as file:
#     #这里要干的事情,干完之后自动关闭文件
#     csv_reader=csv.reader(file) #读取csv文件并存放在csv_reader变量中
#     for row in csv_reader:
#         print(row)#获取csv_reader变量里的每一行

#把csv文件读取为字典格式
# with open('data.csv','r',encoding='utf-8') as file2:
#     csv_reader2=csv.DictReader(file2)
#     for row in csv_reader2:
#         print(f"姓名:{row['name']},年龄:{row['age']},城市:{row['city']},工资{row['salary']}")

#写入csv文件
#准备数据
# data=[
#     ['姓名','年龄','性别','电话'],
#     ['张三','18','男','123456'],
#     ['往三', '19', '男', '123456'],
#     ['里三', '19', '男', '123456'],
#     ['五三', '10', '男', '123456'],
#
# ]
# with open('data.csv','w',encoding='utf-8',newline='') as file3:
#     csv_writer=csv.writer(file3)
#     csv_writer.writerows(data)

#写入字典数据
data=[{'姓名':'张三','年龄':'19','性别':'男'},
      {'姓名':'张1','年龄':'19','性别':'男'},
      {'姓名':'张2','年龄':'19','性别':'男'},
      {'姓名':'张3','年龄':'19','性别':'男'}]
#打开文件
fieldnames = ['姓名', '年龄', '性别']

with open('data.csv','w',encoding='utf-8',newline='') as file2:
    csv_dict_writer=csv.DictWriter(file2,fieldnames=fieldnames)
    csv_dict_writer.writeheader() #为什么要写这一行?因为属性头
    csv_dict_writer.writerows(data)